<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\park\Hub;
use app\admin\model\park\ParkingPlace;
use app\admin\model\park\Region;
use app\common\library\ParkService;

use think\LoggerInterface;

/**
 * 停车收费接口
 */
class Park extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $logger;
   
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * 获取控制端下属停车位
     *
     * @param string $hub_id 控制端id
     */
    public function getParkingPlace()
    {
        $hub_id = $this->request->request("hub_id");
       
        if (!$hub_id) {
            $this->error(__('hub_id不正确'));
        }
        $list = ParkingPlace::where('hub_id', $hub_id)->select();
        $list = collection($list)->toArray();
        $this->success(__('获取成功'), $list);
    }

    /**
     * 更新控制端下属停车位在线状态
     * ([{"id":1, "online_status": "online"}, {"id":2, "online_status": "offline"}])
     * 
     * @ApiMethod   (POST)
     */
    public function updateParkingPlaceOnlineStatus()
    { 
        $json = $this->request->post();
        foreach ($json as $key) {
            if(isset($key['online_status']) && ($key['online_status'] == 'online' || $key['online_status'] == 'offline')){
                Db::name('parking_place')
                    ->where('id', $key['id'])
                    ->update([
                        'online_status'		=>	$key['online_status']
                    ]);
            }
        }
        
        $this->success(__('成功'));
    }

    /**
     * 接收地磁感应通知
     */
    public function notify()
    { 
        $data = $this->request->post();
        if(isset($data["IMEI"]) && isset($data["messageType"]) && isset($data['payload'])) {
            $imei = $data['IMEI'];
            $messageType = $data['messageType']; // dataReport signalReport
            // 数据上报
            if($messageType == "dataReport"){
                $payload = $data['payload'];
                $parking_state = $payload['parking_state'];
                $device = ParkingPlace::where('device_imei', $imei)->find();
                if($device) {
                    \think\Hook::listen("upload_car_status", ['device' => $device, 'car_status' => $parking_state]);
                    $device->car_status = ($parking_state == 1 ? 1 : 0);
                    $device->save();

                    if($device->status = 'wait' && $parking_state == 0) {
                        // TODO: 打开地桩， 把地桩状态从wait改成idle
                        
                        try {
                            $openresullt = ParkService::Open($device->id);
                            if($openresullt == "success") {
                                $device->status = 'idle';
                                $device->save();
                                $this->logger->error("打开地桩({$device->id})成功：".$openresullt);
                            } else {
                                $this->logger->error("打开地桩({$device->id})失败：".$openresullt);
                            }
                        } catch (\Exception $e) {
                            $this->logger->error("打开地桩({$device->id})失败：".$e->getMessage());
                        }
                    }

                }
            }
        }
        
    }
}
